<template>
  <div>
    <div class="top">
      <!-- 头部标题 -->
      <div>
        <h1 class="title01">水分管理</h1>
      </div>
      <!-- 搜索和新增功能 -->
      <div class="right">
        <el-form
          :model="Inquireform"
          label-width="auto"
          :rules="rules"
          ref="formSearch"
        >
          <div class="query">
            <el-form-item prop="searchText">
              <el-input
                v-model.number="Inquireform.searchText"
                @input="handleQuery"
                placeholder="输入浇水天数进行查询"
              ></el-input>
            </el-form-item>
            <el-button type="primary" @click="Search(Inquireform)"
              >搜索</el-button
            >
          </div>
        </el-form>
        <div>
          <el-button
            type="primary"
            @click="handleAddNew"
            :disabled="soil.data === null"
            >新增</el-button
          >
        </div>
      </div>
    </div>
    <!-- 列表数据 -->
    <div>
      <el-table :data="indexedData" style="width: 100%" empty-text="暂无数据">
        <el-table-column prop="plantname" label="植物名" />
        <el-table-column fixed prop="index" label="序号" width="80" />
        <el-table-column prop="wateringamount" label="浇水量(毫升)" />
        <el-table-column prop="wateringmode" label="浇水方式" />
        <el-table-column prop="wateringfrequency" label="浇水天数" />
        <!-- <el-table-column prop="sid" label="土地" width="120" /> -->
        <el-table-column prop="createtime" label="创建时间" />
        <el-table-column prop="username" label="创建人" width="120" />
        <el-table-column prop="remark" label="删除原因" />
        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <!-- <el-button
              link
              type="primary"
              size="small"
              @click="openEditDialog(scope.row)"
              :class="{ deleted: scope.row.deleted === 1 }"
              :disabled="scope.row.deleted === 1"
              >编辑</el-button
            > -->
            <el-button
              link
              type="primary"
              size="small"
              @click="openEditDelete(scope.row)"
              :class="{ deleted: scope.row.deleted === 1 }"
              :disabled="scope.row.deleted === 1"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 删除通知 -->
    <el-dialog v-model="dialogFormDelate" title="删除" width="500">
      <el-form :model="form" ref="ruleFormRefDelete" :rules="soilRules">
        <el-form-item
          label="删除原因"
          :label-width="formLabelWidth"
          prop="remark"
        >
          <el-input
            v-model.trim="form.remark"
            :rows="2"
            type="textarea"
            placeholder="请输入原因"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormDelate = false">取消</el-button>
          <el-button type="primary" @click="submitDelete(ruleFormRefDelete)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <div>
      <div class="example-pagination-block">
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :current-page="currentPage"
          :pageSize="pageSize"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 新增弹窗 -->
    <div>
      <el-dialog v-model="dialogFormVisibleAdd" title="新增" width="500">
        <el-form :model="form" ref="ruleFormRef" :rules="soilRules">
          <!-- 新增浇水量 -->
          <el-form-item
            label="浇水量"
            :label-width="formLabelWidth"
            prop="wateringamount"
          >
            <el-input v-model.trim="form.wateringamount" autocomplete="off">
              <template #append>毫升</template>
            </el-input>
          </el-form-item>
          <!-- 新增浇水方式 -->
          <el-form-item
            label="浇水方式"
            :label-width="formLabelWidth"
            prop="wateringmode"
          >
            <el-select
              v-model.trim="form.wateringmode"
              placeholder="请选择"
              clearable
            >
              <el-option label="喷灌" value="0" />
              <el-option label="滴灌" value="1" />
            </el-select>
          </el-form-item>
          <!-- 新增浇水天数 -->
          <!-- <el-form-item
            label="新增浇水天数"
            :label-width="formLabelWidth"
            prop="wateringfrequency"
          >
            <el-input v-model.trim="form.wateringfrequency" autocomplete="off">
              <template #append>天</template>
            </el-input>
          </el-form-item> -->
          <!-- 新增设备名 -->
          <!-- <el-form-item label="设备名" :label-width="formLabelWidth" prop="did">
            <el-select v-model.trim="form.did" placeholder="请选择" clearable>
              <el-option
                v-for="item in ActiveData"
                :key="item.did"
                :label="item.dname"
                :value="item.did"
              />
            </el-select>
          </el-form-item> -->
          <!-- 新增创建人 -->
          <!-- <el-form-item
            label="创建人"
            :label-width="formLabelWidth"
            prop="username"
          >
            <el-input v-model="form.username" autocomplete="off" />
          </el-form-item> -->
          <!-- 新增备注 -->
          <!-- <el-form-item
            label="备注"
            :label-width="formLabelWidth"
            prop="remark"
          >
            <el-input
              v-model.trim="form.remark"
              :rows="2"
              type="textarea"
              maxlength="30"
              show-word-limit
              placeholder="请输入备注"
            />
          </el-form-item> -->
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="resetForm">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, computed } from "vue";
import {
  getList,
  getSearch,
  getDelete,
  getAdd,
  getUpdate,
  waterdevice,
} from "@/api/Water/index";

// 输入框的长度
const formLabelWidth = "140px";
// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref([]);
onMounted(() => {
  getListitem();
  getSoildevice();
});
// 新增弹窗
const dialogFormVisibleAdd = ref(false);
// 新增框ref
const ruleFormRef = ref(null);
//编辑框
// const ruleFormRefPut = ref(null);
// 删除弹窗
const dialogFormDelate = ref(false);
// 删除框
const ruleFormRefDelete = ref(null);
// 页码更改
const handleCurrentChange = (newPage) => {
  console.log("newPage", newPage);
  currentPage.value = newPage;
  getListitem(newPage);
};

// 查询设备状态
const soil = ref([]);
const getSoildevice = () => {
  waterdevice().then((res) => {
    soil.value = res;
    if (soil.value.data === null) {
      ElMessage({
        message: "当前没有设备不能新增",
        type: "error",
        plain: true,
      });
    }
    console.log("soildevice.value ", soil.value);
  });
};
// 每页条数更改
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
  getListitem(1);
};

// 清空表单
const resetForm = () => {
  form.wateringamount = "";
  form.wateringmode = "";
  form.wateringfrequency = "";
  form.did = "";
  form.username = "";
  form.remark = "";
  dialogFormVisibleAdd.value = false;
};
// 打开新增对话框重置表单
const handleAddNew = () => {
  resetForm();
  dialogFormVisibleAdd.value = true;
};

// 获取列表数据
const getListitem = () => {
  getList({
    pageNum: currentPage.value,
    pageSize: pageSize.value,
  }).then((res) => {
    tableData.value = res.data.records.filter((it) => {
      if (it.wateringmode == 1) {
        it.wateringmode = "滴灌";
        return it;
      } else {
        it.wateringmode = "喷灌";
        return it;
      }
    });
    console.log("tableData.value", tableData.value);

    total.value = res.data.total;
  });
};

// 设置序号
const indexedData = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value + 1;

  return tableData.value.map((item, index) => ({
    ...item,
    index: startIndex + index,
  }));
});

// 搜索
const Inquireform = ref({
  searchText: "",
});
// 校验输入的内容
const rules = reactive({
  searchText: [
    { required: true, message: "请输入浇水天数", trigger: "blur" },
    { type: "number", message: "请输入正确的数字值", trigger: "blur" },
  ],
});
// 搜索
const Search = (form) => {
  console.log("搜索内容", form.searchText);
  if (!form.searchText) {
    ElMessage({
      message: "请输入数据",
      type: "error",
      plain: true,
    });
    getListitem();
  } else {
    getSearch(form.searchText).then((res) => {
      tableData.value = res.data.records;
      total.value = res.data.total;
      currentPage.value = 1; // 重置当前页为第一页
    });
  }
};

// 校验的内容
const form = reactive({
  wateringamount: "",
  wateringmode: "",
  // wateringfrequency: "",
  // did: "",
  remark: "",
  // username:"",
});

//校验输入的内容
const soilRules = reactive({
  wateringamount: [
    { required: true, message: "请输入浇水量", trigger: "blur" },
    { validator: checkWater, trigger: "blur" },
  ],
  wateringmode: [
    { required: true, message: "请选择浇水方式", trigger: "change" },
  ],
  // wateringfrequency: [
  //   { required: true, message: "请输入浇水天数", trigger: "blur" },
  // ],
  // did: [{ required: true, message: "请选择设备", trigger: "blur" }],
  // // username: [{ required: true, message: "请输入创建人", trigger: "blur" }],
  remark: [{ required: true, message: "请输入内容", trigger: "blur" }],
});
function checkWater(rule, value, callback) {
  if (value <= 0) {
    return callback(new Error("浇水量不能小于等于0"));
  } else {
    return callback();
  }
}
//新增提交按钮
const submitForm = (ruleFormRef) => {
  console.log("ruleFormRef", ruleFormRef);
  // 验证表单
  ruleFormRef.validate((valid) => {
    if (valid) {
      // 验证通过，提交表单
      getAdd(form)
        .then((res) => {
          if (res.code == 200) {
            // 清空并关闭新增输入框内容
            resetForm();
            // 重新获取列表数据
            getListitem();
          } else {
            // 处理错误情况
            console.error("添加失败:", res.message);
          }
        })
        .catch((error) => {
          console.error("请求错误:", error);
        });
    } else {
      // 验证失败，提示用户
      console.log("验证失败");
    }
  });
};
// 要编辑栏的数据
// const openEditDialog = (row) => {
//   form.wid = row.wid;
//   form.wateringamount = row.wateringamount;
//   form.wateringmode = row.wateringmode;
//   form.wateringfrequency = row.wateringfrequency;
//   form.did = row.did;
//   // form.username = row.username;
//   form.remark = row.remark;
//   // 显示编辑对话框
//   dialogFormVisible.value = true;
// };
// 要删除栏的数据
const openEditDelete = (row) => {
  form.wid = row.wid;
  form.remark = row.remark;
  // 显示对话框
  dialogFormDelate.value = true;
};

//编辑
// const submitSave = (ruleFormRefPut) => {
//   console.log("ruleFormRefPut", ruleFormRefPut);
//   ruleFormRefPut.validate((valid) => {
//     if (valid) {
//       // 验证通过，提交表单
//       getUpdate(form)
//         .then((res) => {
//           console.log("form", form);
//           if (res.code == 200) {
//             // 关闭对话框
//             dialogFormVisible.value = false;
//             // 清空新增输入框内容
//             // resetUpdate();
//             // 重新获取列表数据
//             getListitem();
//           } else {
//             // 处理错误情况
//             console.error("编辑失败:", res.message);
//           }
//         })
//         .catch((error) => {
//           console.error("请求错误:", error);
//         });
//     } else {
//       // 验证失败，提示用户
//       console.log("验证失败");
//     }
//   });
// };

//修改删除原因
const submitDelete = (openEditDelete) => {
  console.log("openEditDelete", openEditDelete);
  openEditDelete.validate((valid) => {
    if (valid) {
      // 验证通过，提交表单
      getUpdate(form)
        .then((res) => {
          if (res.code == 200) {
            console.log("formform", form);

            // 关闭对话框
            dialogFormDelate.value = false;
            dialogDelate(form);
            // 重新获取列表数据
            getListitem();
          } else {
            // 处理错误情况
            console.error("编辑失败:", res.message);
          }
        })
        .catch((error) => {
          console.error("请求错误:", error);
        });
    } else {
      // 验证失败，提示用户
      console.log("验证失败");
    }
  });
};
// 删除
const dialogDelate = (row) => {
  console.log("删除------", row);

  getDelete(row.wid)
    .then((res) => {
      console.log("res---------", res);
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        // 重新获取列表数据
        getListitem();
      } else {
        // 删除失败的提示
        ElMessage({
          type: "error",
          message: "删除失败: " + res.message,
        });
      }
    })
    .catch((error) => {
      console.error("请求错误:", error);
      // 请求错误的提示
      ElMessage({
        type: "error",
        message: "请求错误",
      });
    });
};
</script>

<style lang="scss" scoped>
.top {
  height: 2vh;
  padding: 10px 0;
  border-radius: 5px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  margin-top: 10px;

  /*顶部标题 */
  // .title01 {
  //   font-size: 20px;
  //   font-weight: bold;
  //   border-left: 5px solid #409eff;
  //   padding-left: 10px;
  // }
  .right {
    display: flex;
    .query {
      display: flex;
      margin-right: 20px;
    }
  }
}
</style>
